package com.jh.paymentchannel.payment;

import static io.jsonwebtoken.lang.Strings.hasText;

/**
 * @author Yichuan
 * @version 1.0
 */
public enum TradeStatus {

    WAIT_BUYER_PAY(0, "WAIT_BUYER_PAY", "创建"),

     TRADE_SUCCESS(1, "TRADE_SUCCESS", "成功"),

    TRADE_FAILURE(2, "TRADE_FAILURE", "失败"),

    TRADE_FINISHED(3, "TRADE_FINISHED", "完结"),

    TRADE_CLOSED(4, "TRADE_CLOSED", "关闭"),

    TRADE_REFUND(5, "TRADE_REFUND", "转入退款"),

    TRADE_REVOKED(6, "TRADE_REVOKED", "已撤销"),

    TRADE_PAYING(7, "TRADE_PAYING", "用户支付中"),


    ;

    final short value;
    final String code;
    final String desc;

    TradeStatus(int value, String code, String desc) {
        this.value = (short) value;
        this.code = code;
        this.desc = desc;
    }

    public short getValue() {
        return value;
    }

    public String getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    public static <T extends Number> TradeStatus of(T n) {
        short v;
        if (n == null || (v = n.shortValue()) < 0) {
            return null;
        }
        for (TradeStatus ts: values()) {
            if (ts.getValue() == v) {
                return ts;
            }
        }
        return null;
    }

    public static TradeStatus of(String code) {
        if (!hasText(code)) {
            return null;
        }
        String _code = code.toUpperCase();
        if (!_code.contains("TRADE") && !_code.equals("WAIT_BUYER_PAY")) {
            _code = "TRADE_" + _code;
        }
        for (TradeStatus ts: values()) {
            if (ts.getCode().equals(_code)) {
                return ts;
            }
        }
        return null;
    }

    public static TradeStatus wechatState(String state) {
        switch (state) {
            case "SUCCESS":
                return TradeStatus.TRADE_SUCCESS;
            case "REFUND":
                return TradeStatus.TRADE_REFUND;
            case "NOTPAY":
                return TradeStatus.WAIT_BUYER_PAY;
            case "CLOSED":
                return TradeStatus.TRADE_CLOSED;
            case "REVOKED":
                return TradeStatus.TRADE_REVOKED;
            case "USERPAYING":
                return TradeStatus.TRADE_PAYING;
            case "PAYERROR":
                return TradeStatus.TRADE_FAILURE;
            case "FAIL":
                return TradeStatus.TRADE_FAILURE;
        }
        return null;
    }
}
